package C034;

/**
 * ClassName: C01
 * Package: C034
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/4 15:42
 * @Version 1.0
 * @Since 1.0
 */
public class C01 {

    // 提交时不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    public static ListNode getIntersectionNode(ListNode h1, ListNode h2) {
        if(h1 == null || h2 == null) {
            return null;
        }
        // 计算两链表的长度差
        ListNode p1 = h1, p2 = h2;
        int diff = 0;
        while (p1.next != null) {
            p1 = p1.next;
            diff++;
        }
        while (p2.next != null) {
            p2 = p2.next;
            diff--;
        }

        // 判断是否有相交的节点
        if(p1 != p2) {
            return null;
        }

        if(diff >= 0) {
            p1 = h1;
            p2 = h2;
        } else {
            p1 = h2;
            p2 = h1;
        }
        diff = Math.abs(diff);
        while(diff-- > 0) {
            p1 = p1.next;
        }

        // 查看第一个相交的节点
        while(p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }

}
